//
//  MediaFile.swift
//  VPai
//
//  Created by devel on 16/9/12.
//  Copyright © 2016年 viatech. All rights reserved.
//

import Foundation
import SwiftyJSON

class MediaFile: NSObject {
    let type : MediaType
    var path : String
    var size : Int
    let time : Double //timeIntervalSince1970
    var nameWithExt : String = ""
    var nameWithoutExt : String = ""
    var sizeString : String = ""
    var name2DateString : String = ""
    var name2HourMin : String = ""
    var name2Time : Double = 0
    
    var thumbnailurl : String?
    var thumbnail : UIImage?
    var downloading = false
    var downloadProgress = 0
    
    init(type: MediaType, path: String, size: Int, time: Double){
        
        self.type = type
        self.path = path
        self.size = size
        self.time = time
        
        super.init()
        
        nameWithExt = fnameWithExt()
        nameWithoutExt = fnameWithoutExt()
        sizeString = fsizeString()
        name2DateString = fname2DateString()
        name2HourMin = fname2HourMin()
        name2Time = fname2Time()
    }
    
    //return 20160908101233.jpg
    private func fnameWithExt() -> String {
        let ns  = NSString(string: path)
        return ns.lastPathComponent
    }
    
    //return 20160908101233
    private func fnameWithoutExt() -> String {
        let ns  = NSString(string: nameWithExt)
        return ns.stringByDeletingPathExtension
    }
    
    //return 102.23MB
    private func fsizeString() -> String {
        let sizeFloat = Float(size)/1024.0
        if sizeFloat < 0 {
            return "0KB"
        }else if sizeFloat < 1024.0 {
            return String(format: "%.02fKB", sizeFloat)
        }else if sizeFloat < 1024.0 * 1024.0 {
            return String(format: "%.02fMB", (sizeFloat/1024.0))
        }else {
            return String(format: "%.02fGB", (sizeFloat/(1024.0*1024.0)))
        }
    }
    
    //根据文件名返回日期,如果文件名无法获得日期，则根据time时间来计算
    //20160908101233.jpg
    //return 2016-09-08
    private func fname2DateString() -> String {
        var substring = ""
        var count = 0
        for s in nameWithoutExt.characters {
            if s == "-" {
                break
            }
            if s >= "0" && s <= "9" {
                substring += String(s)
                count += 1
                if count >= 14 {
                    break
                }
            }
        }
        
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyyMMddHHmmss"
        
        if let d = dateFormatter.dateFromString(substring){
            dateFormatter.dateFormat = "yyyy-MM-dd"
            return dateFormatter.stringFromDate(d)
        }else {
            dateFormatter.dateFormat = "yyyy-MM-dd"
            let real = NSDate(timeIntervalSince1970: time)
            return dateFormatter.stringFromDate(real)
        }
    }
    
    //根据文件名返回timeIntervalSince1970,如果文件名无法获得，则根据返回time
    private func fname2Time() -> Double {
        var substring = ""
        var count = 0
        for s in nameWithoutExt.characters {
            if s == "-" {
                break
            }
            if s >= "0" && s <= "9" {
                substring += String(s)
                count += 1
                if count >= 14 {
                    break
                }
            }
        }
        
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyyMMddHHmmss"
        
        if let d = dateFormatter.dateFromString(substring){
            return d.timeIntervalSince1970
        }else {
            return time
        }
    }
    
    //根据文件名返回小时分钟,如果文件名无法获得，则根据time时间来计算
    //20160908101233.jpg
    //return 10:12
    private func fname2HourMin() -> String {
        var substring = ""
        var count = 0
        for s in nameWithoutExt.characters {
            if s == "-" {
                break
            }
            if s >= "0" && s <= "9" {
                substring += String(s)
                count += 1
                if count >= 14 {
                    break
                }
            }
        }
        
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyyMMddHHmmss"
        
        if let d = dateFormatter.dateFromString(substring){
            dateFormatter.dateFormat = "HH:mm"
            return dateFormatter.stringFromDate(d)
        }else {
            dateFormatter.dateFormat = "HH:mm"
            let real = NSDate(timeIntervalSince1970: time)
            return dateFormatter.stringFromDate(real)
        }
    }
    
    static func parseFromJson(json: SwiftyJSON.JSON) -> MediaFile{
        let filename = json["filename"].string ?? ""
        let path = json["url"].string ?? ""
        let size = json["size"].string ?? ""
        let modifytime = json["modifytime"].string ?? ""
        let thumbnailurl = json["thumbnailurl"].string ?? ""
        let type = getMediaType(filename)
        let file = MediaFile(type: type, path: path, size: Int(size)!, time: Double(modifytime)!)
        file.thumbnailurl = thumbnailurl
        return file
    }
    
    
    static func parseFromAnyObject(obj: AnyObject) -> MediaFile{
       // Log.info("obj", msg: "parseFromAnyObject:\(SwiftyJSON.JSON(obj))")
        let json = SwiftyJSON.JSON(obj)
        let filename = json["Key"].string ?? ""
        let path = json["Key"].string ?? ""
        let size = json["Size"].string ?? ""
        //let modifytime = json["LastModified"].string ?? ""
        let thumbnailurl = json["thumbnailurl"].string ?? ""
        let type = getMediaType(filename)
        let file = MediaFile(type: type, path: path, size: Int(size)!, time: 0/*Double(modifytime)!*/)
        file.thumbnailurl = thumbnailurl
        return file
    }
    
    static func parseFromAnyJson(json: SwiftyJSON.JSON) -> MediaFile{
        let filename = json["Key"].string ?? ""
        let path = OSSManager.getDownloadPath(filename)
        let size = json["Size"].string ?? ""
        let type = getMediaType(filename)
        //let modifytime = json["LastModified"].string ?? ""
        let thumbnailurl = type == MediaType.VIDEO ? getThumbUrl(filename):path
        let file = MediaFile(type: type, path: path, size: Int(size)!, time: 0/*Double(modifytime)!*/)
        file.thumbnailurl = thumbnailurl
        return file
    }
    static func getThumbUrl(key:String)->String?{
        let arrayString = key.characters.split(".").map(String.init)
        if(arrayString.count >= 2){
            return OSSManager.getDownloadPath("\(arrayString[0])_thumb.jpg")
        }
        return nil
    }
    static func getMediaType(name: String) -> MediaType{
        let s = name.lowercaseString
        if s.hasSuffix("jpg") || s.hasSuffix("png"){
            return MediaType.IMAGE
        }else if s.hasSuffix("mp4") || s.hasSuffix("m4v") {
            return MediaType.VIDEO
        }
        return MediaType.UNKNOWN
    }
}


enum MediaType{
    case  VIDEO, IMAGE, UNKNOWN
}